import socket
import time
import threading
import os
from semantic_nav.log_utils import get_logger
logger = get_logger()


def recv_all(sock, bufsize):
    if sock is None:
        return None
    # receive data from the socket until the buffer is full or no more data is available
    data = b""
    while True:
        part = sock.recv(bufsize)
        data += part
        if len(part) < bufsize:
            break
    return data


class SocketClient:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.socket = None

    def __del__(self):
        # close connection
        try:
            if self.socket is not None:
                self.socket.shutdown(socket.SHUT_RDWR)
                self.socket.close()
            logger.info("client deconstructor")
        except Exception as e:
            logger.info(e)

    def create_connection(self):
        if self.socket is not None:
            self.socket.close()
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        while True:
            try:
                self.socket.connect((self.host, self.port))
                logger.info(f"Successfully connected to server on {self.host}:{self.port}")
                return True
            except Exception as e:
                logger.error(e)
                time.sleep(1)

    def send(self, message):
        if self.socket is None:
            self.create_connection()
        try:
            self.socket.sendall(message.encode("utf-8"))
            return True
        except Exception as e:
            logger.error(e)
            self.socket.close()
            self.socket = None
            return False

    def recv(self, bufsize=1024):
        if self.socket is None:
            self.create_connection()
        try:
            data = recv_all(self.socket, 1024)
            if data:
                res = data.decode('utf-8')
                logger.info(f"Data received from server: {res}")
                return res
        except Exception as e:
            logger.error(e)
            self.socket.close()
            self.socket = None
            return None


class SocketServer:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.setblocking(False)
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.client_socket = None
        self.client_address = None

    def __del__(self):
        try:
            if self.client_socket is not None:
                self.client_socket.shutdown(socket.SHUT_RDWR)
                self.client_socket.close()
            self.server_socket.shutdown(socket.SHUT_RDWR)
            self.server_socket.close()
            logger.info("Server deconstructor")
        except Exception as e:
            logger.error(e)

    def start(self):
        server_address = (self.host, self.port)
        self.server_socket.bind(server_address)
        """ The listen() function sets the socket to listening mode, putting the server socket into a state where it waits for incoming connections.
        When a new connection request arrives, if the queue is full, the server will reject the connection;
        otherwise, the server will create a new socket specifically to handle the connection request and return that socket to the client.
        backlog: Specifies the maximum number of pending connections in the queue. """
        self.server_socket.listen(1)

    def accept_client(self) -> bool:
        # close the previous connection
        if self.client_socket is not None:
            self.client_socket.shutdown(socket.SHUT_RDWR)
            self.client_socket.close()
            self.client_socket = None
        # receive client connection
        try:
            self.client_socket, self.client_address = self.server_socket.accept()
            self.client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            logger.info(f"Successfully connected to client on {self.client_address}")
            return True
        except Exception:
            return False

    def spin(self):
        while not self.accept_client():
            logger.info("Wait for client connection...")
            time.sleep(1)

    def send(self, message):
        if self.client_socket is None:
            self.spin()
        try:
            self.client_socket.sendall(message.encode("utf-8"))
            return True
        except BrokenPipeError:
            # If a BrokenPipeError occurs while sending data, it indicates that the receiving end has disconnected.
            self.client_socket.close()
            self.client_socket = None
            return False
        except Exception as e:
            logger.info(e)
            return False

    def recv(self):
        if self.client_socket is None:
            self.spin()
        try:
            data = recv_all(self.client_socket, 1024)
            if data:
                res = data.decode('utf-8')
                logger.info(f"Data received from client: {res}")
                return res
        except socket.error as e:
            logger.error(e)
            self.client_socket.close()
            self.client_socket = None
            return None


if __name__ == "__main__":
    socket_ip = os.getenv('SOCKET_IP', '127.0.0.1')
    socket_port = int(os.getenv('SOCKET_PORT', '10086'))
    # Create SocketServer instance
    server = SocketServer(socket_ip, socket_port)
    server_thread = threading.Thread(target=server.accept_client)
    server_thread.start()
    # Create SocketClient instance
    client = SocketClient(socket_ip, socket_port)
    # Send message to server and receive response from server
    client.send("Hello, server!")
    server.recv()
    server_thread.join()
